package com.lzf.trace.modules.scan.avtivity;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.huawei.agconnect.AGConnectInstance;
import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.cloud.database.AGConnectCloudDB;
import com.huawei.agconnect.cloud.database.CloudDBZone;
import com.huawei.agconnect.cloud.database.CloudDBZoneConfig;
import com.huawei.agconnect.cloud.database.CloudDBZoneObjectList;
import com.huawei.agconnect.cloud.database.CloudDBZoneQuery;
import com.huawei.agconnect.cloud.database.CloudDBZoneSnapshot;
import com.huawei.agconnect.cloud.database.exceptions.AGConnectCloudDBException;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.lzf.trace.IBaseActivity;
import com.lzf.trace.R;
import com.lzf.trace.modules.manage.dto.AddEvent;
import com.lzf.trace.modules.manage.dto.ObjectTypeInfoHelper;
import com.lzf.trace.modules.manage.dto.Product;
import com.lzf.trace.publics.utils.EmptyUtils;
import com.lzf.trace.publics.utils.L;
import com.lzf.trace.publics.utils.T;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.DateUnit;

import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ImageView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ResultActivity extends IBaseActivity {
    AGConnectCloudDB mCloudDB;
    CloudDBZoneConfig mConfig;
    CloudDBZone mCloudDBZone;

    private String code;

    private QMUITopBar mTopbar;

    private LinearLayout error_view_ll, success_view_ll, main_head_ll;
    private TextView code_tv, endtime_tv, name_tv, model_tv, factory_tv, createtime_tv, batch_tv, endtime_tv2, yxq_title_tv, main_head_tv;
    private ImageView yxq_title_iv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);

        initViews();
        initDatas();
    }


    @Override
    public void initViews() {
        code = getIntent().getStringExtra("code");

        mTopbar = findViewById(R.id.topbar);
        mTopbar.setTitle("溯源结果");
        mTopbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        error_view_ll = findViewById(R.id.error_view_ll);
        success_view_ll = findViewById(R.id.success_view_ll);
        main_head_ll = findViewById(R.id.main_head_ll);
        main_head_tv = findViewById(R.id.main_head_tv);
        yxq_title_tv = findViewById(R.id.yxq_title_tv);
        yxq_title_iv = findViewById(R.id.yxq_title_iv);

        code_tv = findViewById(R.id.code_tv);
        endtime_tv = findViewById(R.id.endtime_tv);
        name_tv = findViewById(R.id.name_tv);
        model_tv = findViewById(R.id.model_tv);
        factory_tv = findViewById(R.id.factory_tv);
        createtime_tv = findViewById(R.id.createtime_tv);
        batch_tv = findViewById(R.id.batch_tv);
        endtime_tv2 = findViewById(R.id.endtime_tv2);

    }

    @Override
    public void initDatas() {
        initCloudDatabase();
    }

    private void initCloudDatabase() {
        //初始化云数据库
        AGConnectCloudDB.initialize(getApplicationContext());
//        AGConnectOptions agcConnectOptions = new AGConnectOptionsBuilder().setRoutePolicy(AGCRoutePolicy.CHINA).build(mContext);
//        AGConnectInstance instance = AGConnectInstance.buildInstance(agcConnectOptions);
        AGConnectInstance instance = AGConnectInstance.getInstance();
        mCloudDB = AGConnectCloudDB.getInstance(instance, AGConnectAuth.getInstance(instance));
        try {
            mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
            mConfig = new CloudDBZoneConfig("trace",
                    CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
                    CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
            mConfig.setPersistenceEnabled(true);
            Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);
            openDBZoneTask.addOnSuccessListener(new OnSuccessListener<CloudDBZone>() {
                @Override
                public void onSuccess(CloudDBZone cloudDBZone) {
                    L.i("open clouddbzone", "open cloudDBZone success");
                    mCloudDBZone = cloudDBZone;
                    //开始获取数据
                    getData();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(Exception e) {
                    L.e("open clouddbzone", "open cloudDBZone failed for " + e.getMessage());
                }
            });
        } catch (AGConnectCloudDBException e) {
            T.showShort(mContext, "initialize CloudDB failed:" + e.toString());
        }

    }

    private void getData() {
        CloudDBZoneQuery<Product> query = CloudDBZoneQuery.where(Product.class).equalTo("code", code);
        queryProductInfo(query);
    }

    private void queryProductInfo(CloudDBZoneQuery<Product> query) {
        if (mCloudDBZone == null) {
            return;
        }
        Task<CloudDBZoneSnapshot<Product>> queryTask = mCloudDBZone.executeQuery(query,
                CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
        //List<personInfo> tmpInfoList = new ArrayList<>();
        queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<Product>>() {
            @Override
            public void onSuccess(CloudDBZoneSnapshot<Product> snapshot) {
                processQueryResult(snapshot);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(final Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        T.showShort(mContext, "获取数据失败！" + e.toString());
                    }
                });
            }
        });
    }

    private void processQueryResult(CloudDBZoneSnapshot<Product> snapshot) {
        CloudDBZoneObjectList<Product> bookInfoCursor = snapshot.getSnapshotObjects();
        List<Product> bookInfoList = new ArrayList<>();
        try {
            while (bookInfoCursor.hasNext()) {
                Product mProduct = bookInfoCursor.next();
                bookInfoList.add(mProduct);
            }
        } catch (AGConnectCloudDBException e) {
            L.e("query data", "processQueryResult: " + e.getMessage());
        }
        snapshot.release();

        if (bookInfoList.size() > 0) {
            Product product = bookInfoList.get(0);
//            code_tv, endtime_tv, name_tv, model_tv, factory_tv, createtime_tv, batch_tv, endtime_tv2;
            code_tv.setText(product.getCode());
            endtime_tv.setText("有效期至：" + product.getEndtime());
            name_tv.setText(product.getName());
            model_tv.setText(product.getModel());
            factory_tv.setText(product.getFactory());
            createtime_tv.setText(product.getCreatetime());
            batch_tv.setText(product.getBatch());
            endtime_tv2.setText(product.getEndtime());

            if (EmptyUtils.isNotEmpty(product.getEndtime())) {
                Date date = DateUtil.parse(product.getEndtime());
                long betweenDay = DateUtil.between(date, new Date(), DateUnit.DAY, false);
                if (betweenDay > 0) {
                    main_head_ll.setBackgroundResource(R.color.error_red);
                    main_head_tv.setText("追溯码验证通过，已超期");
                    yxq_title_tv.setText("在有效期外");
                    yxq_title_iv.setImageResource(R.drawable.icon_ch);
                }
            }

            error_view_ll.setVisibility(View.GONE);
            success_view_ll.setVisibility(View.VISIBLE);
        } else {
            T.showShort(mContext, "没有结果");
            error_view_ll.setVisibility(View.VISIBLE);
            success_view_ll.setVisibility(View.GONE);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            mCloudDB.closeCloudDBZone(mCloudDBZone);
        } catch (AGConnectCloudDBException e) {
            e.printStackTrace();
        }
    }

}